package filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户认证过滤器
 * 在做某些操作或者进入某些页面的时候，先判断用户是否登录，如果没有登录，则跳转到登录页面
 * @author Administrator
 *
 */
public class UserAuthFilter implements Filter{
	private FilterConfig config;

	public void destroy() {
		
	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		
		String mappingRequest = config.getInitParameter("mappingRequest");
		String[] requests = mappingRequest.split(",");
		String path = (String) request.getAttribute("path");
		if (contains(requests, path) && request.getSession().getAttribute("user") == null) {//这些请求需要进行认证
			response.sendRedirect(request.getContextPath() + "/user/logInOut/toLogin.do");
		} else {
			arg2.doFilter(request, response);
		}
	}

	public void init(FilterConfig arg0) throws ServletException {
		this.config = arg0;
	}
	
	private boolean contains(String[] arr, String str){
		for (int i = 0; i < arr.length; i++) {
			if (arr[i].equals(str)) {
				return true;
			}
		}
		return false;
	}

}
